package com.khalil.kkadmin.infrastructure.web.security;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.ttl.TransmittableThreadLocal;

public class WebContext {

    private static final TransmittableThreadLocal<String> usernameLocal = new TransmittableThreadLocal<>();

    public static void setUsername() {
        if (StpUtil.isLogin()) {
            String username = StpUtil.getLoginIdAsString();
            usernameLocal.set(username);
        }
    }

    public static void clearUsername() {
        usernameLocal.remove();
    }

    public static String getUsername() {
        return usernameLocal.get();
    }

    public static LoginInfo getUserInfo() {
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        Boolean isLogin = tokenInfo.getIsLogin();
        String username = (String) tokenInfo.getLoginId();
        String tokenName = tokenInfo.getTokenName();
        String tokenValue = tokenInfo.getTokenValue();
        return LoginInfo.builder().isLogin(isLogin).username(username).tokenName(tokenName).tokenValue(tokenValue).build();
    }

    /**
     * 登录
     *
     * @param username 用户名
     */
    public static void login(String username) {
        StpUtil.login(username);
    }

    /**
     * 登出
     */
    public static void logout() {
        StpUtil.logout();
    }
}
